package client;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import model.Model;
import model.ServerRequest;

public class Connection implements Runnable{

	private final String host;
	private final int port;
	private final Model data;

	private final Executor executor = Executors.newCachedThreadPool(new DaemonThreadFactory());
	
	/**
	 * Returns only daemon threads for tasks
	 */
	private class DaemonThreadFactory implements ThreadFactory{
		@Override public Thread newThread(Runnable r) {
			Thread t = new Thread(r);
			t.setDaemon(true);
			return t;
		}
	}
			
	public Connection(Model m) {
		data = m;
		host = Settings.getInstance().getHost();
		port = Settings.getInstance().getPort();
	}
	
	@Override
	public void run() {
		ServerRequest sr = null;
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			// A try to get the request
			sr = data.getRequest();
			if (sr == null) continue;

			executor.execute(new RequestHandler(host, port, sr));
		}
	}

}
 